<template>
  <el-dialog v-model="dialogVisible" title="新建设备" width="1000">
    <div style="display: flex; justify-content: center; align-items: center;margin: 20px 0;">
      <el-form :model="addEngineInfo" label-position="left" label-width="auto" size="large" style="width: 800px"
        :rules="rules" ref="formDom">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="addEngineInfo.name" placeholder="填写设备名称" />
        </el-form-item>
        <el-form-item label="状态">
          <el-segmented v-model="addEngineInfo.status" :options="Status" :formatter="statusMap" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="addEngineInfo.typeCode" placeholder="请选择类型">
            <el-option v-for="devType in deviceTypeArr" :value="devType.type" :label="devType.desc"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主机" prop="host">
          <el-input v-model="addEngineInfo.host" placeholder="填写主机" />
        </el-form-item>
        <el-form-item label="中间件" prop="mid">
          <el-input v-model="addEngineInfo.mid" placeholder="填写中间件标识" />
        </el-form-item>
        <el-form-item label="数据流" prop="dataFlow">
          <el-input v-model="addEngineInfo.dataFlow" placeholder="填写数据流" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer" style="display: flex; justify-content: center; align-items: center;">
        <el-button type="primary" @click="addEngine">
          提交
        </el-button>
        <el-button type="primary" @click="resetForm">
          清空
        </el-button>
      </div>
    </template>
  </el-dialog>
  <div class="container" :class="{ hasForm: showAddWindow == true }">
    <div class="body">
      <div class="box">
        <div class="topBtns">
          <el-button type="primary" class="topBtn" @click="showDialog">新建设备</el-button>
          <el-button type="primary" class="topBtn" @click="refresh">刷新</el-button>
        </div>
        <!-- 内容展示 -->
        <div class="contents">
          <div class="content">
            <!-- 数据列名 -->
            <el-table :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
              :data="engineArr" style="width: 100%;height: 650px;" max-height="600px" fit="false">
              <el-table-column prop="did" label="设备标识码did" width="150" />
              <el-table-column prop="name" label="设备名称/name" width="150">
                <template #default="scope">
                  <el-input v-if="scope.row.isEdit" v-model="scope.row.name" placeholder="请输入设备名称"></el-input>
                  <div v-else>{{ scope.row.name }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="typeCode" label="设备类型/type" width="180">
                <template #default="scope">
                  <el-select v-if="scope.row.isEdit" v-model="scope.row.typeCode" placeholder="请选择类型">
                    <el-option v-for="devType in deviceTypeArr" :key="devType.type" :label="devType.desc"
                      :value="devType.type"></el-option>
                  </el-select>
                  <div v-else>{{ typeFormatter(scope.row, column) }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="设备状态/status" width="150" :formatter="statusMap">
                <template #default="scope">
                  <el-select v-if="scope.row.isEdit" v-model="scope.row.status" placeholder="请选择状态"
                    :formatter="typeFormatter">
                    <el-option v-for="status in Status" :label="status" :value="getNoByStatus(status)"></el-option>
                  </el-select>
                  <div v-else>{{ statusMap(scope.row, column) }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="host" label="主机/host" width="120">
                <template #default="scope">
                  <el-input v-if="scope.row.isEdit" v-model="scope.row.host" placeholder="请输入主机"></el-input>
                  <div v-else>{{ scope.row.host }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="mid" label="中间件标识码/mid" width="150" />
              <el-table-column prop="dataFlow" label="数据流/dataFlow" width="400">
                <template #default="scope">
                  <el-input v-if="scope.row.isEdit" v-model="scope.row.dataFlow" placeholder="请输入数据流"></el-input>
                  <div v-else>{{ scope.row.dataFlow }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间/createTime" width="200" :formatter="formatterTime" />
              <el-table-column prop="updateTime" label="更新时间/updateTime" width="200" :formatter="formatterTime" />
              <el-table-column fixed="right" label="操作" min-width="250">
                <template #default="scope">
                  <el-button link type="primary" v-if="!scope.row.isEdit"
                    @click.prevent="startEdit(scope.$index, scope.row)">
                    修改
                  </el-button>
                  <el-button link type="primary" v-if="scope.row.isEdit"
                    @click.prevent="saveModify(scope.$index, scope.row)">
                    保存
                  </el-button>
                  <el-button link type="primary" v-if="scope.row.isEdit"
                    @click.prevent="cancelEdit(scope.$index, scope.row)">
                    取消
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- 页切换 -->
        <div class="bottom">
          <div class="bottom_left">共有&nbsp;{{ total }}&nbsp;项</div>
          <el-pagination layout="prev, pager, next" :total="total" :page-size="pageSize" @current-change="changePage" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, toRaw } from 'vue'
import { addDeviceData, modifyDevice, reqDeviceData, reqDeviceStatus, reqDeviceTypeData } from '@/api/device';
import { ElMessage } from 'element-plus';
import { getStatus, Status, getNoByStatus } from '@/constant/status';
import { useRouter } from 'vue-router';
import { en } from 'element-plus/es/locale/index.mjs';

// 加载数据
const initData = async () => {
  engineArr_unprocessed.splice(0, engineArr_unprocessed.length)
  engineArr.splice(0, engineArr.length)
  try {
    let res = await reqDeviceData(pageNo.value, pageSize.value)
    switch (res.code) {
      case 0:
        total.value = Number(res.data.total)
        engineArr_unprocessed.push(...res.data.records)
        engineArr.push(...processData(res.data.records))
        break
      case 1:
        setTimeout(() => { $router.push('/login') }, 1000)
        break
      case 2:
        break
    }
  } catch (err) {
    ElMessage({
      type: 'error',
      message: err.message
    })
  }
}
// el-dialog
const dialogVisible = ref(false)
const showDialog = () => {
  dialogVisible.value = true
}

const startEdit = (index, row) => {
  row.isEdit = true
}
// 保存修改
const saveModify = async (index, row) => {
  let modifyData = {
    id: engineArr_unprocessed[index].id,
    name: row.name,
    typeCode: row.typeCode,
    host: row.host,
    status: row.status,
    mid: engineArr_unprocessed[index].mid,
    dataFlow: row.dataFlow,
  }
  try {
    let res = await modifyDevice(modifyData)
    switch (res.code) {
      case 0:
        ElMessage({
          type: "success",
          message: "操作成功"
        })
        row.isEdit = false
        Object.assign(engineArr_unprocessed[index], row)
        Object.assign(engineArr[index], row)
        break
      case 1:
        setTimeout(() => { $router.push('/login') }, 1000)
        break
      case 2:
        break
    }
  }
  catch (err) {
    ElMessage({
      type: 'error',
      message: err.message
    })
  }
}
// 取消编辑
const cancelEdit = (index, row) => {
  Object.assign(engineArr[index], engineArr_unprocessed[index])
  row.isEdit = false
}

// 表单dom
let formDom = ref()

// 状态转换
const statusMap = (row, column) => {
  return getStatus(row.status)
}
// 表格时间格式化
const formatterTime = (row, column) => {
  return row[column.property].substr(0, 10)
}
// 设备类型格式化
const typeFormatter = (row, column) => {
  return deviceTypeArr[row.typeCode - 1]?.desc
}
// 当前页号
let pageNo = ref(1)
// 页面大小
let pageSize = ref(10)

// 表单显示控件
let showAddWindow = ref(false)
// 新建设备表单内容
let addEngineInfo = reactive({
  name: null, //设备名
  typeCode: null, //设备类型
  host: null, //主机
  status: null, //1：可用，2不可用，3暂时不可用
  mid: null, //设备标识
  dataFlow: null //数据流
})
// 设备类型表
let deviceTypeArr = reactive([])
// 设备组
let engineArr = reactive([])
// 设备组（未处理）
let engineArr_unprocessed = reactive([])
const processData = (data) => {
  return data.map(item => {
    return {
      ...item,
      isEdit: false,
    }
  })
}
// 设备总数
let total = ref(0)
// 路由
let $router = useRouter()
// 删除设备

// 校验规则
const rules = {
  name: [
    { type: "string", required: true, message: '请输入设备名称', trigger: ['blur', 'change'] }
  ],
  typeCode: [
    { type: "Number", required: true, message: '请输入协议', trigger: ['blur', 'change'] }
  ],
  host: [
    { type: "string", required: true, message: '请输入主机', trigger: ['blur', 'change'] }
  ],
  mid: [
    { type: "string", required: true, message: '请输入设备标识', trigger: ['blur', 'change'] }
  ],
  dataFlow: [
    { type: "string", required: true, message: '请输入数据流', trigger: ['blur', 'change'] }
  ],
}

// 清空表单
const resetForm = () => {
  for (let key in addEngineInfo) {
    addEngineInfo[key] = null
  }
}


//新建设备确认提交
const addEngine = async () => {
  console.log(addEngineInfo)
  let validRes = true
  await formDom.value.validate((valid) => {
    if (!valid) {
      validRes = false
      return false
    }
    return true
  })
  if (!validRes || addEngineInfo.status == null || addEngineInfo.typeCode==null) {
    ElMessage({
      type: "error",
      message: '信息缺漏，请检查'
    })
    return;
  }
  try {
    let arr = []
    let reqData = toRaw(addEngineInfo)
    reqData.status = getNoByStatus(addEngineInfo.status)
    arr.push(reqData)
    let res = await addDeviceData(arr)
    switch (res.code) {
      case 0:
        if (res.data.success == true) {
          ElMessage({
            type: "success",
            message: "操作成功"
          })
          resetForm()
          dialogVisible.value = false
          refresh()
        }
        else {
          ElMessage({
            type: "error",
            message: "新建设备失败"
          })
        }
        break
      case 1:
        setTimeout(() => { $router.push('/login') }, 1000)
        break
      case 2:
        break
    }
  } catch (err) {
    ElMessage({
      type: 'error',
      message: err.message
    })
  }
}
// 页面改变
const changePage = async (newPage) => {
  pageNo.value = newPage
  await initData()
}
const refresh = async () => {
  await initData()
}
onMounted(async () => {
  // 请求设备数据
  await initData()
  // 设备类型列表获取
  let deviceTypeRes = await reqDeviceTypeData()
  switch (deviceTypeRes.code) {
    case 0:
      deviceTypeArr.push(...deviceTypeRes.data)
      break
    case 1:
      setTimeout(() => { $router.push('/login') }, 1000)
      break
    case 2:
      break
  }
})
</script>

<style lang="scss" scoped>
* {
  box-sizing: border-box;
}

.active {
  color: rgb(24, 148, 197) !important;
}

.hidden {
  display: none !important;
}


.container {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;

  .body {
    margin-top: 20px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex: 1;
    color: rgb(156, 153, 153);

    .box {
      margin: 20px;
      width: 85%;
      height: 96%;
      background-color: white;
      padding: 20px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      border: 1px solid rgb(178, 178, 178);
      box-shadow: 0.5px 0.5px 1px 1px rgb(196, 196, 196);

      .topBtns {
        width: 100%;
        height: 5%;
        font-weight: 700;
        margin-left: 20px;
        display: flex;

        .topBtn {
          flex-grow: 0;
          box-sizing: border-box;
          padding-left: 10px;
          padding-right: 10px;
        }
      }


      .contents {
        margin-top: 10px;
        display: flex;
        box-sizing: border-box;
        width: 100%;
        height: 90%;

        .content {
          height: 100%;
          width: 100%;
          box-sizing: border-box;
          flex-direction: column;

        }
      }

      .bottom {
        display: flex;
        width: 100%;
        padding-left: 20px;
        padding-right: 20px;
        box-sizing: border-box;
        // height: 50px;
        align-items: center;
        justify-content: space-between;
      }
    }
  }
}
</style>